import socket from '@ohos.net.socket';
import { BasicDecoder } from '../BasicDecoder';
import { Address, BasicNetworkUtil, Type } from '../BasicNetworkUtil';


export class UdpUtils extends BasicNetworkUtil { //UDP通信工具类
  private socket = socket.constructUDPSocketInstance();

  constructor(decoder: BasicDecoder, type: Type, address: Address, sendSocket: boolean) {
    super(decoder, type, address);
    this.init();
  }

  public close() {
    this.socket.close().then((value) => {
      console.log('close success aaa');
    }).catch((error) => {
      console.log('close error');
    });
  }

  public recvBinary(callback: (data: ArrayBuffer) => void): void {
    this.socket.on('message', value => {
      callback(value.message)
    });
  }

  public init(): Promise<void> {
    return new Promise(() => {
      this.socket.bind({ address: this.address.ip, port: this.address.port, family: 1 }).then(() => {
        console.log('bind success');
      }).catch(err => {
        console.log('bind fail' + err);
      });
    })
  }


  public recv(callback: (data: Map<string, number>) => void) {
    this.socket.on('message', value => { // console.log("on message, message:" + JSON.stringify(value));
      //value中的message才是发送过来的数据，并且是ArrayBuffer类型，需要先转成string类型
      // let recvData = this.arrayBufferToString(value.message);
      let recvData = this.decoder.decode(value.message);
      callback(recvData);
      this.socket.send({ address: { address: value.remoteInfo.address, port: value.remoteInfo.port }, data: "hello" });
    }); //此处收到对端发送过来的数据，在此补充数据解析的代码
    /*if(this.isJsonString(recvData)){
      this.transformData(JSON.parse(recvData));
    }*/
  }


  public send(sendDataString: string | ArrayBuffer) {
    if (this.socket) {
      let promise = this.socket.send({
        data: sendDataString,
        address: { address: this.address.ip, port: this.address.port, family: 1 }
      });
      promise.then(() => {
        console.log('send success');
      }).catch(err => {
        console.log('send fail' + err);
      });
    }
  }
}